import { audioSynthesisV1ControllerBatch } from '@/services/auto/audioSynthesis';
import { useMemoizedFn, useRequest } from 'ahooks';
import {
  AUDIO_SYNTHESIS_FINALLY_STATUS_LIST,
  AudioSynthesisStatus,
} from 'common/utils/data';
import {
  createContext,
  PropsWithChildren,
  useEffect,
  useMemo,
  useState,
} from 'react';
interface ContextType {
  addCheckStatusUuid?: (uuid: string) => void;
  globalWorkList?: API.GlobalResGlobalWorkListItem[];
  checkStatusMap?: Record<string, API.AudioSynthesisIndexEarbuds2EarbudsResult>;
}
export const Context = createContext<ContextType>({});

export default function Provider({
  globalWorkList,
  onCheckStatusUuidsChange,
  children,
}: PropsWithChildren<{
  globalWorkList?: API.GlobalResGlobalWorkListItem[];
  onCheckStatusUuidsChange: (uuids: string[]) => void;
}>) {
  const [checkStatusUuids, setCheckStatusUuids] = useState<string[]>([]);

  const { data } = useRequest(
    () =>
      audioSynthesisV1ControllerBatch({
        uuids: checkStatusUuids.join(','),
      }),
    {
      ready: !!checkStatusUuids.length,
      pollingInterval: 3000,
      onSuccess: (res) => {
        const finishList = res.filter((item) =>
          AUDIO_SYNTHESIS_FINALLY_STATUS_LIST.includes(
            item.status as AudioSynthesisStatus,
          ),
        );
        if (finishList.length) {
          const finishUuids = finishList.map((item) => item.uuid);
          setCheckStatusUuids((origin) => {
            return origin.filter((item) => !finishUuids.includes(item));
          });
        }
      },
    },
  );

  useEffect(() => {
    onCheckStatusUuidsChange(checkStatusUuids);
  }, [checkStatusUuids]);

  const map = useMemo(() => {
    return data?.reduce((obj, item) => {
      return {
        ...obj,
        [item.uuid]: item,
      };
    }, {});
  }, [data]);

  const addCheckStatusUuid: ContextType['addCheckStatusUuid'] = useMemoizedFn(
    (uuid) => {
      if (!checkStatusUuids.includes(uuid)) {
        setCheckStatusUuids((origin) => {
          return origin.concat([uuid]);
        });
      }
    },
  );

  return (
    <Context.Provider
      value={{
        addCheckStatusUuid,
        checkStatusMap: map,
        globalWorkList,
      }}
    >
      {children}
    </Context.Provider>
  );
}
